from django.shortcuts import render, redirect
from django.http import HttpResponse
from user.models import User


# Create your views here.


def login_view(request):
    if request.method == 'GET':
        return render(request, 'user/login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not username or not password:
            return HttpResponse('用户名或密码不能为空')
        try:
            user = User.objects.get(username=username, password=password)
        except:
            return HttpResponse('用户名或密码错误')
        if user.password != password:
            return HttpResponse('用户名或密码错误')
        request.session['uname'] = user.username
        request.session['uid'] = user.id
        return redirect('/')


def reg_view(request):
    if request.method == 'GET':
        return render(request, 'user/reg.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        passwd = request.POST.get('passwd')
        if not username or not password or not passwd:
            return HttpResponse('用户名或密码不能为空')
        user = User.objects.filter(username=username)
        if user:
            return HttpResponse('用户名已存在，请重新输入')
        if password != passwd:
            return HttpResponse('两次密码不一致')
        User.objects.create(username=username, password=password)
        return redirect('/')


def logout_view(request):
    if 'uname' in request.session and 'uid' in request.session:
        del request.session['uname']
        del request.session['uid']
        return redirect('/')
    return HttpResponse('请登录后进行操作!')
